<template>
  <el-upload
    class="avatar-uploader"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="uploadImage"
    action=""
  >
    <!-- action=""
   :on-success="handleAvatarSuccess" 配套使用-->
    <img v-if="value" :src="value" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKID1yqzJTWQ6ZbaO0NgrriPuHEh5IMRQK8s',
  SecretKey: 'mQs67xeATYUI2e9Vhy51oXp1a2IMFxSl'
}) // 完成cos对象的初始化
// 选择图片上传

export default {
  props: {
    value: {
      type: String,
      default: ''
    }

  },
  data() {
    return {

    }
  },
  methods: {
    // 上传前校验
    beforeAvatarUpload(file) {
      // 白名单判断
      console.log(file)
      const isJPG = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 图片 格式!')
        return false
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
        return false
      }
    },
    uploadImage(e) {
      // console.log(e)
      cos.putObject({
        Bucket: 'local-1320584039', // 存储桶名称
        Region: 'ap-guangzhou', // 地域名称
        Key: e.file.name, // 文件名称
        StorageClass: 'STANDARD', // 固定值
        Body: e.file // 文件对象
      }, (err, data) => {
        if (!err) {
          // 拿到了腾讯云返回的地址
          // 通过input自定义事件将地址传出去
          console.log(data)
          this.$emit('input', 'http://' + data.Location) // 将地址返回了
        }
      })
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

